import { useState, useEffect } from 'react'
import { Table, Space,  Button, Popconfirm, message } from 'antd';
import MyModel from './components/MyModel'
import { useSelector, useDispatch } from 'react-redux'
import { Actions } from 'store/actionCreator'

const Login = () => {
  const [record, setRecord] = useState<any>({})
  const [btnMsg, setBtnMsg] = useState<string>('')
  const [visible, setVisible] = useState(false);
  const [confirmLoading] = useState(false);
  const [saveForm, setSaveForm] = useState<any>();
  const { queryList, tableStatus } = useSelector((s:any) => {
    console.log(s, 's')
    return s
  })
  const dispatch = useDispatch();

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: (text: string) => <a>{text}</a>,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '数量',
      dataIndex: 'skuCount',
      key: 'skuCount',
    },
    {
      title: '头像',
      dataIndex: 'imgUrl',
      key: 'imgUrl',
      render: (text:string, record: any) => {
        return <>
         <img style={{width: 50, height: 50}} src={record.imgUrl} alt="" />
         </>
      }
    },
    {
      title: 'Action',
      key: 'action',
      render: (text: string, record: {name: string}) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <Popconfirm
            title="Are you sure to delete this task?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <a href="#">Delete</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    dispatch(Actions.getQueryList())
  }, [])

  useEffect(() => {
    // 提交查询数据接口 tableStatus === 'add'
    if (tableStatus !== '') {
      dispatch(Actions.getQueryList())
      // 当数据添加/编辑成功之后，让状态回到初始值
      dispatch(Actions.updateTableStatus())
    }
  }, [tableStatus])

  // 2. 编辑和添加的功能函数
  const handleOk = (form: any) => {
    const formItem = form.getFieldsValue();
    if (btnMsg === 'edit'){
      // 调用了一个异步函数 （promise.then async await）
      dispatch(Actions.getUpdateItem({...record, ...formItem}))
    } else {
      dispatch(Actions.getAddItem({...record, ...formItem}))
    }
    // 当编辑 添加成功后，重新调用数据渲染数据
    // dispatch(Actions.getQueryList())
    setVisible(false);
  };

  // 3. 点击调用增加弹出框
  const handleAddItem = () => {
    showModal()
    setBtnMsg('add')

    // 对象 -> 引用 指针
    saveForm.setFieldsValue({
      price: '',
      skuCount: '',
      imgUrl: ''
    })
  }

  // 4. 点击调用编辑弹出框
  const handleEdit = (record: any) => {
    showModal()
    setBtnMsg('edit')
    setRecord({...record})
    saveForm.setFieldsValue({...record})
  }

  // 5. 删除确认 - 处理删除弹出框事件
  const confirm =  (record:any) => {
    console.log('delete----1')
    dispatch(Actions.getDelteItem({ id: record.id }))
    console.log('delete----2')
    // dispatch(Actions.getQueryList())
  }

  // 6. 删除取消
  const cancel = (e:any) => {
    message.error('Click on No');
  }

  // 7. 弹出框确认关闭
  const showModal = () => {
    setVisible(true);
  };

  // 8. 弹出框关闭
  const handleCancel = () => {
    console.log('Clicked cancel button');
    setVisible(false);
  };

  // // 自定义回调函数
  const getFormInstance = (form:any) => {
    // 接收到，保存form
    setSaveForm(form)
  }

  return <div>
    <Button type="primary" onClick={handleAddItem}>添加数据</Button>
    <MyModel
      handleOk={handleOk}
      handleCancel={handleCancel}
      getFormInstance={(form:any) => getFormInstance(form)}
      visible={visible}
      confirmLoading={confirmLoading}
    />
    <Table
      // rowSelection={rowSelection}
      columns={columns}
      dataSource={queryList}
    />

  </div>
}

export default Login;



// import { FC, useState, useEffect } from 'react'
// import { useTranslation } from "react-i18next";
// import i18n from "i18next";
// import {  } from 'antd'

// const Login:FC = () => {
//   const [lang, setLang] = useState<string>('');
//   // 自定义的hook
//   const { t } = useTranslation();

//   return <>
//    <select onChange={(e) => {
//      console.log(e.target.value, 'e')
//      i18n.changeLanguage(e.target.value)
//    }}>
//      <option value="en">英文</option>
//      <option value="zh">中文</option>
//    </select>
//    <h1>{t('msg')}</h1>
//   </>;
// }

// export default Login;
